<template>
    <div>
      <!--      面包屑导航-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!--      卡片视图区-->
      <el-card>
<!--        警告区域-->
          <el-alert
            title="注意，只允许为第三级分类设置参数！"
            type="warning"
            show-icon>
          </el-alert>

<!--       选择商品分类区-->
        <el-row>
          <el-col :span="8" class="cat_opt">
            <span>选择商品分类:</span>
            <!--          级联选择框-->
            <el-cascader
              v-model="selectKeys"
              :options="categoryList"
              :props="cateProps"
              clearable
              @change="handleChange">
            </el-cascader>
          </el-col>
        </el-row>

<!--        tab页签区-->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="many">
            <el-row>
              <el-col :span="2">
                <el-button type="primary" size="mini" :disabled="isDisable" @click="addDialogVisible = true">添加参数</el-button>
              </el-col>
            </el-row>
            <!--      参数列表区-->
            <el-table :data="manyTableDate" border stripe unique-opened>
              <!--              展开行-->
              <el-table-column type="expand">
                <template scope="scope">
                  <el-tag
                    v-for="(item,index) in scope.row.attr_vals"
                    :key="index"
                    closable
                    @close="handleClose(index,scope.row)">
                    {{item}}
                  </el-tag>
                  <!--                  添加标签-->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!--          索引列-->
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="attr_name" label="属性名称"></el-table-column>
              <el-table-column label="操作">
                <!--            作用域插槽-->
                <template slot-scope="scope">
                  <!--             修改按钮-->
                  <!--              open-delay延迟出现，单位毫秒 enterable 鼠标是否可进入到 tooltip 中-->
                  <el-tooltip effect="dark" content="修改参数" placement="top" :open-delay=openDelay :enterable="false">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="setParamsShowDialog(scope.row)">修改参数</el-button>
                  </el-tooltip>
                  <!--              删除按钮-->
                  <el-tooltip effect="dark" content="删除参数" placement="top" :open-delay=openDelay :enterable="false">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletParam(scope.row)">删除参数</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态属性" name="only">
            <el-row>
              <el-col :span="2">
                <el-button type="primary" size="mini" :disabled="isDisable" @click="addDialogVisible = true">添加属性</el-button>
              </el-col>
            </el-row>
            <!--      参数列表区-->
            <el-table :data="onlyTableDate" border stripe>
              <!--              展开行-->
              <el-table-column type="expand">
                <template scope="scope">
                  <el-tag
                    v-for="(item,index) in scope.row.attr_vals"
                    :key="index"
                    closable
                    @close="handleClose(index,scope.row)">
                    {{item}}
                  </el-tag>
                  <!--                  添加标签-->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <!--          索引列-->
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <!--            作用域插槽-->
                <template slot-scope="scope">
                  <!--             修改按钮-->
                  <!--              open-delay延迟出现，单位毫秒 enterable 鼠标是否可进入到 tooltip 中-->
                  <el-tooltip effect="dark" content="修改参数" placement="top" :open-delay=openDelay :enterable="false">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="setParamsShowDialog(scope.row)">修改参数</el-button>
                  </el-tooltip>
                  <!--              删除按钮-->
                  <el-tooltip effect="dark" content="删除参数" placement="top" :open-delay=openDelay :enterable="false">
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deletParam(scope.row)">删除参数</el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

<!--        添加动态参数对话框-->
        <el-dialog
          :title="'添加'+lableTitle"
          :visible.sync="addDialogVisible"
          width="50%"
          @close="dialogClose('addParamRef')">
          <el-form :model="addForm" :rules="addRules" ref="addParamRef" label-width="100px">
            <el-form-item :label="lableTitle" prop="attr_name">
              <el-input v-model="addForm.attr_name" clearable></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams()">确 定</el-button>
           </span>
        </el-dialog>

        <!--       修改参数对话框-->
        <el-dialog
          :title="'修改'+lableTitle"
          :visible.sync="setDialogVisible"
          width="50%"
          @close="dialogClose('setParamRef')">
          <el-form :model="addForm" :rules="addRules" ref="setParamRef" label-width="100px">
            <el-form-item :label="lableTitle" prop="attr_name">
              <el-input v-model="addForm.attr_name" clearable></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="setParams()">确 定</el-button>
           </span>
        </el-dialog>
      </el-card>
    </div>
</template>

<style scoped>
  .cat_opt {
    margin: 15px 0 15px -17px
  }
  .el-cascader {
    margin-left: 5px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 100px;
    margin-left: 10px;
  }
</style>

<script>
export default {
  data () {
    return {
      // 分类数据列表集合
      categoryList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: false,
        // 触发方式，默认点击触发，hover鼠标移上去即可触发
        expandTrigger: 'hover'
      },
      // 选中的父级id数组
      selectKeys: [],
      // 被激活页面名称
      activeName: '',
      // 获取的动态参数列表数据
      manyTableDate: [],
      // 获取的静态参数列表数据
      onlyTableDate: [],
      openDelay: 500,
      // 添加参数开关
      addDialogVisible: false,
      // 修改参数开关
      setDialogVisible: false,
      // 当前要修改的属性
      attribute: {},
      // 添加参数请求数据
      addForm: {
        attr_name: ''
      },
      // 添加表单的验证规则
      addRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 获取分类列表
    async getCategoryList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.categoryList = res.data
    },
    // 添加分类选择项发生变化触发函数
    parentCateChange() {
      if (this.selectKeys.length !== 3) {
        // 选中的不是三级分类
        this.selectKeys = []
      } else {
        // 选中的是三级分类
        console.log(this.selectKeys)
      }
    },
    // 获取参数列表数据
    async getParamsList() {
      if (this.selectKeys.length !== 3 || this.activeName === '0') {
        this.onlyTableDate = []
        this.manyTableDate = []
        return null
      }
      // 获取对应的参数列表
      const { data: res } = await this.$http.get(`categories/${this.selectKeys[2]}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      // 将attr_vals转换成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框输入的数据
        item.inputValue = ''
      })
      console.log(res.data)
      console.log(res.data[0].attr_vals)
      if (this.activeName === 'many') this.manyTableDate = res.data
      this.onlyTableDate = res.data
    },
    // tab页签点击事件的处理函数
    handleClick() {
      this.getParamsList()
    },
    // 级联选择框改变触发事件
    handleChange() {
      this.getParamsList()
    },
    // 弹框关闭事件
    dialogClose(name) {
      this.$refs[name].resetFields()
    },
    // 添加参数
    addParams() {
      this.$refs.addParamRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.selectKeys[2]}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        //  隐藏添加对话框
        this.addDialogVisible = false
        //  刷新列表
        this.getParamsList()
        this.$message.success('添加参数成功')
      })
    },
    // 修改属性对话框
    async setParamsShowDialog(at) {
      this.attribute = at
      this.addForm.attr_name = at.attr_name
      console.log(this.attribute)
      this.setDialogVisible = true
    },
    async setParams() {
      this.$refs.setParamRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.selectKeys[2]}/attributes/${this.attribute.attr_id}`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        //  隐藏添加对话框
        this.setDialogVisible = false
        //  刷新列表
        this.getParamsList()
        this.$message.success(res.meta.msg)
      })
    },
    async deletParam(at) {
      const attrid = at.attr_id
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消了删除！')
      }
      const { data: res } = await this.$http.delete(`categories/${this.selectKeys[2]}/attributes/${attrid}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      //  刷新列表
      this.getParamsList()
      this.$message.success(res.meta.msg)
    },
    // 添加标签触发
    showInput(row) {
      row.inputVisible = true
      // 让文本框获得焦点
      // $nextTick方法作用：当页面上元素被重新渲染之后才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加标签框失去焦点或按下enter触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue.trim())
        row.inputVisible = false
        row.inputValue = ''
        this.savaAttrValus(row)
      }
      row.inputVisible = false
      row.inputValue = ''
    },
    // 删除标签触发
    async handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.savaAttrValus(row)
    },
    // 保存修改后的标签
    async savaAttrValus(row) {
      // 发起请求，保存修改
      const { data: res } = await this.$http.put(`categories/${this.selectKeys[2]}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      return this.$message.success(res.meta.msg)
    }
  },
  created () {
    this.getCategoryList()
  },
  computed: {
    // tab页签开关
    isDisable() {
      if (this.selectKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    lableTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>
